const wechat = require("co-wechat");
const WechatAPI = require("co-wechat-api");
const moment = require("moment");
const _ = require("lodash");

module.exports = class extends doodoo.Controller {
    /**
     *
     * @api {get} /home/wechat/index 绑定微信公众号
     * @apiDescription 绑定微信公众号
     * @apiGroup App Home
     * @apiVersion 0.0.1
     *
     * @apiSampleRequest /home/wechat/index
     *
     */
    async index() {
        const config = {
            token: process.env.WX_TOKEN,
            appid: process.env.WX_APPID,
            encodingAESKey: process.env.WX_ENCODINGAESKEY
        };
        const api = new WechatAPI(
            process.env.WX_APPID,
            process.env.WX_APPSECRET
        );

        return wechat(config).middleware(async (message, ctx) => {
            console.log(message);
            const userInfo = await api.getUser(message.FromUserName);
            const loginSuccess = async uid => {
                const wxUser = await this.model("wx_user")
                    .query(qb => {
                        qb.where("openid", userInfo.openid);
                    })
                    .fetch({ withRelated: ["custom"] });
                let _wxUser, custom;
                if (!wxUser) {
                    _wxUser = await this.model("wx_user")
                        .forge({
                            openid: userInfo.openid,
                            nickname: userInfo.nickname,
                            sex: userInfo.sex,
                            language: userInfo.language,
                            city: userInfo.city,
                            province: userInfo.province,
                            country: userInfo.country,
                            headimgurl: userInfo.headimgurl
                        })
                        .save();
                } else {
                    _wxUser = await this.model("wx_user")
                        .forge({
                            id: wxUser.id,
                            nickname: userInfo.nickname,
                            sex: userInfo.sex,
                            language: userInfo.language,
                            city: userInfo.city,
                            province: userInfo.province,
                            country: userInfo.country,
                            headimgurl: userInfo.headimgurl
                        })
                        .save();
                    if (!_.isEmpty(wxUser.custom)) {
                        custom = wxUser.custom;
                    }
                }

                const wxUserToken = this.jwtSign(_wxUser);

                // 发送socket通知
                const sid = await this.redis.getAsync(`wxLogin:uid:${uid}:sid`);
                if (sid && io.sockets.sockets[sid]) {
                    const socket = io.sockets.sockets[sid];
                    const event = custom ? "login" : "register";

                    if (custom) {
                        const token = this.jwtSign(custom);
                        socket.emit("wxLoginSuccess", {
                            event,
                            wxUserToken,
                            token,
                            custom
                        });
                    } else {
                        socket.emit("wxLoginSuccess", {
                            event,
                            wxUserToken
                        });
                    }

                    // 删除socket记录
                    await this.redis.delAsync(`wxLogin:uid:${uid}:sid`);
                }

                return {
                    content: `登录成功提醒\n
您好，您已在电脑端成功登录!\n
登录账号： ${userInfo.nickname}
登录时间： ${moment().format("YYYY-MM-DD HH:mm:ss")}\n
如果这不是您的操作，请尽快修改登录密码。`,
                    type: "text"
                };
            };

            if (message.MsgType === "event") {
                if (message.Event === "subscribe") {
                    // 第一次扫描登录
                    if (_.startsWith(message.EventKey, "qrscene_login_")) {
                        return await loginSuccess(message.EventKey.substr(14));
                    }
                }

                if (message.Event === "unsubscribe") {
                    const wxUser = await this.model("wx_user")
                        .query(qb => {
                            qb.where("openid", userInfo.openid);
                        })
                        .fetch();
                    if (wxUser) {
                        await this.model("wx_user")
                            .forge({
                                id: wxUser.id,
                                subscribe: 0
                            })
                            .save();
                    }
                }

                if (message.Event === "SCAN") {
                    // 扫描登录
                    if (_.startsWith(message.EventKey, "login_")) {
                        return await loginSuccess(message.EventKey.substr(6));
                    }
                }
            }
        })(this.ctx, this.next);
    }
};
